package com.isoftstone.permissiondemo;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * 该类适合不理解动态权限时看一看
 */
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_PERMISSION_CALL = 100;
    private static final String CALL_PHONE = Manifest.permission.CALL_PHONE;
    private static final String TAG = "Permission";
    private Button btnCheck, btnShow, btnCall;
    private Intent callIntent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        init();
    }

    private void init() {
        initViews();
        callIntent = new Intent(Intent.ACTION_CALL);
        Uri uri = Uri.parse("tel:" + "10086");
        callIntent.setData(uri);
    }

    private void initViews() {
        btnCheck = (Button) findViewById(R.id.btn_check);
        btnShow = (Button) findViewById(R.id.btn_showtip);
        btnCall = (Button) findViewById(R.id.btn_call);
        btnCheck.setOnClickListener(this);
        btnShow.setOnClickListener(this);
        btnCall.setOnClickListener(this);
    }

    private boolean checkPermission(String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                Log.e("checkPermission", "PERMISSION_GRANTED" + ContextCompat.checkSelfPermission(this, CALL_PHONE));
                return true;
            } else {
                Log.e("checkPermission", "PERMISSION_DENIED" + ContextCompat.checkSelfPermission(this, CALL_PHONE));
                return false;
            }
        } else {
            Log.e("checkPermission", "M以下" + ContextCompat.checkSelfPermission(this, CALL_PHONE));
            return true;
        }
    }

    private void startRequestPermision(String permission) {
        ActivityCompat.requestPermissions(Main2Activity.this, new String[]{android.Manifest.permission.CALL_PHONE}, REQUEST_PERMISSION_CALL);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CALL) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivity(callIntent);
                } else {
                    //如果拒绝授予权限,且勾选了再也不提醒
                    if (!shouldShowRequestPermissionRationale(permissions[0])) {
                        Log.d(TAG, "拒绝授予权限,且勾选了再也不提醒 ");
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("说明")
                                .setMessage("需要使用电话权限，进行电话测试")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        showTipGoSetting();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        return;
                                    }
                                })
                                .create()
                                .show();
                    } else {
                        Log.d(TAG, "拒绝授予权限，但并未勾选再也不提醒");
                        showTipGoSetting();
                    }
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.btn_check:
                int isGrantd = ContextCompat.checkSelfPermission(getApplicationContext(), CALL_PHONE);
                Toast.makeText(Main2Activity.this, "isGrantd" + isGrantd, Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_showtip:
                boolean isShow = ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this, CALL_PHONE);
                Toast.makeText(Main2Activity.this, "isShow" + isShow, Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_call:
                call();
                break;
            default:
                break;
        }
    }

    private void call() {
        if (checkPermission(CALL_PHONE)) {
            startActivity(callIntent);
        } else {
            startRequestPermision(CALL_PHONE);
        }
    }

    /**
     * 用于在用户勾选“不再提示”并且拒绝时，再次提示用户
     */
    private void showTipGoSetting() {
        new AlertDialog.Builder(this)
                .setTitle("电话权限不可用")
                .setMessage("请在-应用设置-权限-中，允许APP使用电话权限来测试")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).setCancelable(false).show();

    }

    /**
     * 打开Setting
     */
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 123)
        {
            //这里的data为空，不清楚怎么回事
            //再次调用该方法如果应用权限开启，可以选择处理
            call();
        }
    }
}
